from tortoise import fields, models
from tortoise.contrib.pydantic import pydantic_model_creator
from typing import List

class User(models.Model):
    """用户模型"""
    id = fields.BigIntField(pk=True)
    username = fields.CharField(max_length=50, unique=True)
    email = fields.CharField(max_length=255, unique=True)
    hashed_password = fields.CharField(max_length=128)
    is_active = fields.BooleanField(default=True)
    is_superuser = fields.BooleanField(default=False)
    create_at = fields.DatetimeField(auto_now_add=True)
    update_at = fields.DatetimeField(auto_now=True)
    
    # 角色关联
    roles: fields.ManyToManyRelation["Role"] = fields.ManyToManyField(
        "models.Role", related_name="users", through="user_roles"
    )

    class Meta:
        table = "users"
        
    def __str__(self):
        return f"{self.username}"

class Role(models.Model):
    """角色模型"""
    id = fields.BigIntField(pk=True)
    name = fields.CharField(max_length=50, unique=True)
    description = fields.CharField(max_length=200, null=True)
    create_at = fields.DatetimeField(auto_now_add=True)
    update_at = fields.DatetimeField(auto_now=True)
    
    # 权限关联
    permissions: fields.ManyToManyRelation["Permission"] = fields.ManyToManyField(
        "models.Permission", related_name="roles", through="role_permissions"
    )

    class Meta:
        table = "roles"

class Permission(models.Model):
    """权限模型"""
    id = fields.BigIntField(pk=True)
    name = fields.CharField(max_length=100)
    code = fields.CharField(max_length=100, unique=True)
    description = fields.CharField(max_length=200, null=True)
    create_at = fields.DatetimeField(auto_now_add=True)
    update_at = fields.DatetimeField(auto_now=True)

    class Meta:
        table = "permissions" 